package xin.mydreams.mybill.widget.bill.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import xin.mydreams.mybill.global.result.GetFormatResult;
import xin.mydreams.mybill.global.result.PostFormatResult;
import xin.mydreams.mybill.global.result.exception.MyException;
import xin.mydreams.mybill.util.ObjectUtil;
import xin.mydreams.mybill.util.UserUtil;
import xin.mydreams.mybill.widget.bill.entity.Bill;
import xin.mydreams.mybill.widget.bill.service.IBillService;
import xin.mydreams.mybill.widget.user.entity.User;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/bill")
public class BillController {

    @Autowired
    private IBillService billService;

    /**
     * 增
     */
    @PostFormatResult(value = "/addBill")
    public Object addBill(double money, String remarks) {
        Bill bill = new Bill();
        bill.setMoney(money);
        bill.setRemarks(remarks);
        bill = billService.save(bill);
        return bill;
    }

    /**
     * 删除
     */
    @PostFormatResult(value = "/deleteBill/{id}")
    public Object deleteBill(@PathVariable(value = "id") String id) throws MyException {
        Bill bill = billService.findById(id);
        if (bill != null) {
            User createdUser = bill.getCreatedUser();
            User user = UserUtil.getUser();
            if (!user.getUserName().equals(createdUser.getUserName())) {
                throw new MyException("只有创建用户可以删除");
            }
            billService.delete(id);
        }
        return "SUCCESS";
    }

    /**
     * 查询
     */
    @GetFormatResult("/pageList")
    public Object pageList(@RequestParam(value = "pageNo", required = false, defaultValue = "0") int pageNo,
                               @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize,
                               @RequestParam(value = "time") String time) {
        Map<String,Object> map=new HashMap<>();
        Page<Bill> billList=billService.pageList(pageNo, pageSize, time);
        if(ObjectUtil.isEmpty(billList)){
            return null;
        }
        map.put("list",billList);
        map.put("group",billService.groupByCreatedUser(time));

        return map;
    }
}
